<?php
class category extends adminController {
    public $_indexView = "admin/category/index";
    public $_listView = "admin/category/list";
    public $_addView = "admin/category/add";
    public $_editView = "admin/category/edit";
    
	public function __construct() {
		parent::__construct ();
	}
	
    public function loadView($temp) {
        if (!isset($temp["data"]))
            $temp["data"] = '';
        $this->load->view("admin/index", $temp);
    }
    
    public function index($parentid=0) {
        $temp["template"] = $this->_listView;
        if($parentid) {
            $temp["data"] = $this->categoryModel->get_order_where(null, 'number', 'asc', array('parentid' => $parentid));
        } else {
            $temp["data"] = $this->categoryModel->get();    
        }
        $temp["selected"] = $parentid;
        $temp['categories'] = $this->categoryModel->get_order_where(null, 'number', 'asc', array('parentid' => 0));
        $this->loadView($temp);
    }
    
    public function add() {
        $temp["template"] = $this->_addView;
        if(!$this->isPost()) {
            $temp["categories"] = $this->categoryModel->get_order_where(null, 'number', 'asc', array('parentid' => 0));
            $this->loadView($temp);
            return;
        }
        $data = $this->input->post();
        $slug = mb_strtolower(url_title(removesign($data['categoryname'])));
        if($this->categoryModel->check_exist('slug', $slug)) {
            $slug = $slug.'-'.random_string('alnum', 4);
        }
        $data['slug'] = $slug;
        $this->categoryModel->insert($data);
        $this->index();
    }
    
    public function edit($id) {
        $temp["template"] = $this->_editView;
        if(!$this->isPost()) {
            $temp["data"] = $this->categoryModel->read($id);
            $temp["categories"] = $this->categoryModel->get_order_where(null, 'number', 'asc', array('parentid' => 0));
            $this->loadView($temp);
            return;   
        }
        $this->categoryModel->update($this->input->post(), array('id' => $id));
        redirect(base_url().$this->_indexView);
    }
    
    public function delete($id) {
        $this->categoryModel->delete($id);
        redirect(base_url().$this->_indexView);
    }
}
?>